//
//  AddressManageViewModel.swift
//  baihuiju
//
//  Created by 赵家彬 on 2018/6/8.
//  Copyright © 2018年 赵家彬. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa

class AddressManageViewModel: NSObject {

    var valid:Observable<(isValid:Bool, tips:String)>!
    var changeAddress:Observable<Bool>!
    
    init(name:Observable<String?>, mobile:Observable<String?>, area:Observable<(title:String, value:String)>, address:Observable<String?>, changeTap:Observable<Void>) {
        
        let combin = Observable
            .combineLatest(name, mobile, area, address) { (name:$0 ?? "", mobile:$1 ?? "", area:$2, address:$3 ?? "") }
            .share(replay: 1)
        
        valid = combin.map { info -> (isValid:Bool, tips:String) in
                let validName = (info.name.count < 10) && (info.name.count > 0)
                let validMobile = info.mobile.isMobile
                let validArea = !info.area.value.isEmpty
                let validAddress = !info.address.isEmpty
                var strTips = ""
                if !validName && !info.name.isEmpty {
                    strTips = "请输入正确的姓名"
                } else if !validMobile && !info.mobile.isEmpty {
                    strTips = "请输入正确的手机号码"
                }
            return (isValid:validName && validMobile && validArea && validAddress, tips:strTips)
            }.share(replay:1)
        
        changeAddress = changeTap.withLatestFrom(combin)
                .flatMapLatest { info -> Observable<Bool> in
                    SVProgressHUD.show()
                    let arrArea = info.area.value.components(separatedBy: "|")
                    return NetworkTool.requestData(url: ActionURL.CHANGE_ADDRESS, param: [
                        "uid":MainTools.shared.userModel?.uid ?? "",
                        "name":info.name,
                        "mobile":info.mobile,
                        "province":arrArea[0],
                        "city":arrArea[1],
                        "area":arrArea[2],
                        "address":info.address,
                        ]).map({ (json) -> Bool in
                            MainTools.makeToast(message: json["message"].stringValue)
                            return true
                        }).catchErrorJustReturn(false)
                }.observeOn(MainScheduler.instance)
                .share(replay:1)
        
    }
    
}
